const { parse } = require('node-xlsx');
const fs = require("fs");
const { resolve } = require('path');
let originData = require('../asset/i18n/index');
const { validateTrans } = require('../common');
/**
 *  * 将翻译文件中符合规则的翻译内容写入英文文件
 *  * 可能会出现中文有的key在英文中找不到
 * @param {object} opts 
 * @param {string} [opts.fromFileName] 翻译来源path
 * @param {string} [opts.toFileName] 结果储存
 * @param {string} [opts.keyIndex] 要替换的内容对应key所在xls column
 * @param {string} [opts.transOutIndex] 要替换的内容所在xls column
 * @param {string} [opts.replaceOriginData] 要替换的数据
 */
function writeXls2Js(opts) {

    let {
        fromFileName = 'i18n',
        toFileName = 'i18n',
        keyIndex = 0,
        transOutIndex = 1,
        replaceOriginData
    } = opts;

    // 文件加后缀
    if (!fromFileName.endsWith(".xls")) {
        fromFileName = `${fromFileName}.xls`
    }
    if (!toFileName.endsWith(".js")) {
        toFileName = `${toFileName}.js`
    }

    // 读取xls文件
    let writePath = resolve(__dirname, '../asset/xls', fromFileName)
    let [{ data }] = parse(writePath);
    let realData = data.splice(1); // 移除标题栏

    // 遍历xls数据
    realData.forEach(value => {

        // 校验词条内容
        // let isPassValidate = validateTrans(value, true);
        // if (!isPassValidate) return;

        // 通过校验的
        let current = replaceOriginData || originData;

        // 分割key 取值
        let keyArr = value[keyIndex].split('.');

        // 翻译结果
        const transOutStr = `${value[transOutIndex]}`


        keyArr.forEach((key, index) => {
            if (typeof current[key] == 'string') {

                // 有翻译结果
                if (transOutStr != '/' && !!transOutStr) {
                    current[key] = getTranResult(transOutStr)
                }
            } else if (typeof current[key] == 'undefined') {
                current[key] = getTranResult(transOutStr)
            } else if (typeof current[key] == 'object') {
                // 有嵌套对象
                current = current[key];
            }
        })
    })
    let outPath = resolve(__dirname, '../asset/i18n', toFileName)
    fs.writeFileSync(outPath, `module.exports = ${JSON.stringify(originData)}`) // 写国际化文件
}

function getTranResult(transOutStr = '') {
    // 多种翻译 取第一个
    let splitStrIndex = transOutStr.indexOf('/');
    if (splitStrIndex === -1) {
        return transOutStr
    } else {
        return transOutStr.slice(0, splitStrIndex);
    }
}


writeXls2Js({
    fromFileName: '0217',
    toFileName: 'zh',
    transOutIndex: 1,
    replaceOriginData: originData
})
writeXls2Js({
    fromFileName: '0217',
    toFileName: 'en',
    transOutIndex: 2,
    replaceOriginData: originData
})
writeXls2Js({
    fromFileName: '0217',
    toFileName: 'fr',
    transOutIndex: 3,
    replaceOriginData: originData
})